package com.nutricia.core.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.nutricia.common.api.enums.UserLoginNameEnums;
import com.nutricia.common.dal.persistant.CmsSystemMenu;
import com.nutricia.common.dal.persistant.SystemUser;
import com.nutricia.common.util.CheckUtil;
import com.nutricia.core.ex.BizErrorCode;
import com.nutricia.core.ex.BizException;
import com.nutricia.core.model.domain.CmsSystemMenuDO;
import com.nutricia.core.model.domain.SystemUserDO;
import com.nutricia.core.service.SystemUserService;
import com.nutricia.core.service.convertor.SystemMenuServiceConvertor;
import com.nutricia.core.service.convertor.SystemUserServiceConvertor;

/**
 * 系统用户serviceImpl
 *
 * @author: huangsheng
 * @date: 2017/10/19
 */
@Service("systemUserService")
public class SystemUserServiceImpl extends AbstractServiceImpl implements SystemUserService {



    /**
     * 用户登入
     *
     * @author: huangsheng
     * @date: 2017/10/23 上午10:57
     */
    @Override
    public String login(String userLoginName, String password, String loginIp) {

        SystemUser systemUser = systemUserMapper.queryUserByLoginName(userLoginName);
        CheckUtil.isTrue(null != systemUser, BizErrorCode.USER_LOGIN_NAME_ERROR, BizErrorCode.USER_LOGIN_NAME_ERROR.getDescription());
        logger.info("用户存在，userState = {}", systemUser.getUserState());
        CheckUtil.isTrue(StringUtils.equals(systemUser.getPassword(), password), BizErrorCode.LOGIN_PASSWORD_ERROR, BizErrorCode.LOGIN_PASSWORD_ERROR.getDescription());
        logger.info("用户输入的登入密码正确");
        CheckUtil.isTrue(StringUtils.equals(systemUser.getUserState(), SystemUser.USER_STATE_NORMAL), BizErrorCode.USER_IS_DISABLE, BizErrorCode.USER_IS_DISABLE.getDescription());

        try {
            logger.info("用户状态有效，更新登入信息, 当前登入IP = {}", loginIp);
            int successUpdateCount = systemUserMapper.updateLoginInfo(loginIp, systemUser.getId());
            logger.info("成功更新{}条记录", successUpdateCount);
        } catch (Exception e) {
            logger.error("更新用户登入信息异常：{}", e);
        }
        return systemUser.getId();
    }

    /**
     * 创建用户
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午1:52
     */
    @Override
    public String createUser(SystemUserDO systemUserDO) {
        int userLoginNameCount = systemUserMapper.checkUserLoginName(systemUserDO.getUserLoginName());
        logger.info("用户名在系统中存在 {} 条", userLoginNameCount);
        CheckUtil.isTrue(userLoginNameCount == 0, BizErrorCode.USER_LOGIN_NAME_IS_EXIST, BizErrorCode.USER_LOGIN_NAME_IS_EXIST.getDescription());

        try {
            SystemUser systemUser = new SystemUser();
            String userId = UUID.randomUUID().toString();
            logger.info("准备创建用户，ID = {}", userId);
            systemUser.setId(userId);
            systemUser.setUserLoginName(systemUserDO.getUserLoginName());
            systemUser.setUserName(systemUserDO.getUserName());
            systemUser.setPassword(systemUserDO.getPassword());
            systemUser.setCreateId(systemUserDO.getCreateId());
            systemUser.setUserMail(systemUserDO.getUserMail());
            int successInsertCount = systemUserMapper.insertUser(systemUser);
            logger.info("成功插入 {} 条数据", successInsertCount);
            return userId;
        } catch (Exception e) {
            logger.error("创建用户时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 批量创建用户角色数据
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午2:23
     */
    @Override
    public void batchCreateUserRole(List<String> roleIds, String userId) {
        try {
            if (CollectionUtils.isNotEmpty(roleIds)) {
                logger.info("新增用户{}的角色", userId);
                userRoleMapper.batchInsertUserRole(roleIds, userId);
            }
        } catch (Exception e) {
            logger.error("创建用户角色时异常：{}", e);
        }
    }

    /**
     * 获取用户所拥有的所有角色id集合
     *
     * @param userId 用户id
     * @author: huangsheng
     * @date: 2017/10/25 下午4:00
     */
    @Override
    public List<String> getUserRoleIds(String userId) {

        logger.info("获取用户id为{}的角色数据", userId);
        return userRoleMapper.queryRoleIdsByUserId(userId);
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户id
     * @author: huangsheng
     * @date: 2017/10/25 下午4:00
     */
    @Override
    public SystemUserDO getUserDOByUserId(String userId) {

        logger.info("获取用户ID为 {} 的用户数据", userId);
        SystemUser systemUser = systemUserMapper.queryUserById(userId);
        CheckUtil.isTrue(null != systemUser, BizErrorCode.USER_IS_NOE_EXIST, BizErrorCode.USER_IS_NOE_EXIST.getDescription());

        return SystemUserServiceConvertor.systemUserConvertToSystemUserDO(systemUser);
    }

    /**
     * 更新用户
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午5:05
     */
    @Override
    public String updateUser(List<String> roleIds, SystemUserDO systemUserDO) {

        SystemUser systemUser = systemUserMapper.queryUserById(systemUserDO.getId());
        CheckUtil.isTrue(null != systemUser, BizErrorCode.USER_IS_NOE_EXIST, BizErrorCode.USER_IS_NOE_EXIST.getDescription());
        int userLoginNameCount = systemUserMapper.checkUserLoginName(systemUserDO.getUserLoginName());
        logger.info("修改的用户名：userLoginName = {}, 用户原用户名 = {}", systemUser.getUserLoginName(), systemUserDO.getUserLoginName());
        if (!StringUtils.equals(systemUser.getUserLoginName(), systemUserDO.getUserLoginName())) {
        	CheckUtil.isTrue(userLoginNameCount == 0, BizErrorCode.USER_LOGIN_NAME_IS_EXIST, BizErrorCode.USER_LOGIN_NAME_IS_EXIST.getDescription());
        }
        try {
            SystemUser updateUser = new SystemUser();
            updateUser.setId(systemUserDO.getId());
            updateUser.setUserLoginName(systemUserDO.getUserLoginName());
            updateUser.setUserName(systemUserDO.getUserName());
            updateUser.setPassword(systemUserDO.getPassword());
            updateUser.setModifyId(systemUserDO.getModifyId());
            updateUser.setUserMail(systemUserDO.getUserMail());

            int successUpdateCount = systemUserMapper.updateSystemUser(updateUser);
            logger.info("成功更新 {} 条数据", successUpdateCount);

            //更新用户角色, 删除后在批量新增过去
            this.updateUserRole(roleIds, systemUserDO.getId());
            return systemUserDO.getId();
        } catch (Exception e) {
            logger.error("更新用户时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 更新用户角色, 删除后在批量新增过去
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午5:14
     */
    private void updateUserRole(List<String> roleIds, String userId) {
        try {
            int successDeleteCount = userRoleMapper.deleteRoleByUserId(userId);
            logger.info("删除用户 {} 下的所有roleId, 成功删除 {} 条数据", userId, successDeleteCount);
        } catch (Exception e) {
            logger.error("删除用户 {} 下的roleId异常 {}", userId, e);
        }
        this.batchCreateUserRole(roleIds, userId);
    }

    /**
     * 修改用户状态，禁用or启用
     *
     * @param userState 用户状态 00启用， 01禁用
     * @param userId    用户id
     * @param modifyId  修改人id
     */
    @Override
    public void updateUserState(String userState, String userId, String modifyId) {
        try {
            int successUpdateCount = systemUserMapper.updateSystemUserState(userState, userId, modifyId);
            logger.info("成功更新 {} 条数据", successUpdateCount);
        } catch (Exception e) {
            logger.error("修改用户状态，禁用or启用时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 根据用户信息查询菜单数据
     *
     * @author: huangsheng
     * @date: 2017/10/26 下午4:57
     */
    @Override
    public List<CmsSystemMenuDO> getUserMenuList(String userLoginName, String userId) {
        try {
            if (StringUtils.equals(UserLoginNameEnums.ADMIN.getKey(), userLoginName)) {
                logger.info("查询admin的菜单数据，所有菜单数据");
                List<CmsSystemMenu> adminMenuList = userUnionMenuUnionPermissionMapper.queryAdminMenu();
                logger.info("一级菜单数量有：{}", null != adminMenuList ? adminMenuList.size() : "菜单数据为空");
                return SystemMenuServiceConvertor.convertToCmsSystemMenuDOs(adminMenuList);
            } else {
                List<String> menuIds = userUnionMenuUnionPermissionMapper.queryUserMenuIds(userId);
                if (CollectionUtils.isNotEmpty(menuIds)) {
                    logger.info("根据用户权限查询出来拥有的菜单ID数量: {}", menuIds.size());
                    List<CmsSystemMenu> userMenuList = userUnionMenuUnionPermissionMapper.queryUserSystemMenu(menuIds);
                    return SystemMenuServiceConvertor.convertToCmsSystemMenuDOs(userMenuList);
                }
            }
            return null;
        } catch (Exception e) {
            logger.error("根据用户信息查询菜单数据时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 根据用户查询出用户拥有的权限codes，去重复
     *
     * @param userId 用户id
     * @return permissionCode 集合
     */
    @Override
    public List<String> getUserPermissionCodes(String userId) {

        return userUnionMenuUnionPermissionMapper.queryUserPermissionCodes(userId);
    }

    /**
     * 通过权限code 集合获取用户权限的用户
     *
     * @param permissionCodes 权限code 集合
     * @return
     */
    @Override
    public List<SystemUserDO> getUerByPermissionCodes(List<String> permissionCodes) {
        List<String> permissionIds = systemPermissionMapper.queryPermissionIdsByPermissionCodes(permissionCodes);
        if (CollectionUtils.isNotEmpty(permissionIds)) {
            List<String> roleIds = rolePermissionMapper.queryRoleIdsByPermissionCodes(permissionIds);
            logger.info("获取到 {} 条角色", CollectionUtils.isNotEmpty(roleIds) ? roleIds.size() : 0);
            if (CollectionUtils.isNotEmpty(roleIds)) {
                List<String> userIds = userRoleMapper.queryUserIdsByRoleIds(roleIds);
                if (CollectionUtils.isNotEmpty(userIds)) {
                    List<SystemUser> systemUsers = systemUserMapper.queryUserByUserIds(userIds);
                    if (CollectionUtils.isNotEmpty(systemUsers)) {
                        List<SystemUserDO> systemUserDOS = new ArrayList<>();
                        systemUsers.forEach(systemUser -> {
                            systemUserDOS.add(SystemUserServiceConvertor.systemUserConvertToSystemUserDO(systemUser));
                        });
                        return systemUserDOS;
                    }
                }
            }
        }
        return ListUtils.EMPTY_LIST;
    }

    /**
     * 通过userId获得userName
     * @param userId 用户ID
     * @return 用户名字
     */
    @Override
    public String getUserNameById(String userId){
        SystemUser systemUser = systemUserMapper.queryUserById(userId);

        if(systemUser != null){
            return systemUser.getUserName();
        }else{
            return null;
        }
    }
}
